<template>
  <div class="cart">
    <h4>全部商品</h4>
    <div class="cart-main">
      <div class="cart-th">
        <div class="cart-th1">全部</div>
        <div class="cart-th2">商品</div>
        <div class="cart-th3">单价（元）</div>
        <div class="cart-th4">数量</div>
        <div class="cart-th5">小计（元）</div>
        <div class="cart-th6">操作</div>
      </div>
      <div class="cart-body">
        <ul
          class="cart-list"
          v-for="(cartInfo, index) in cartInfoList"
          :key="cartInfo.id"
        >
          <li class="cart-list-con1">
            <input
              type="checkbox"
              name="chk_list"
              :checked="cartInfo.isChecked"
              @change="checkCartInfoState(cartInfo)"
            />
          </li>
          <li class="cart-list-con2">
            <img :src="cartInfo.imgUrl" />
            <div class="item-msg">{{ cartInfo.skuName }}</div>
          </li>
          <li class="cart-list-con4">
            <span class="price">{{ cartInfo.skuPrice }}.00</span>
          </li>
          <li class="cart-list-con5">
            <a
              href="javascript:void(0)"
              class="mins"
              @click="changeSkuNum('decrement', cartInfo)"
              >-</a
            >
            <input
              autocomplete="off"
              type="text"
              :value="cartInfo.skuNum"
              minnum="1"
              class="itxt"
              @change="changeSkuNum('change', cartInfo, $event)"
            />
            <a
              href="javascript:void(0)"
              class="plus"
              @click="changeSkuNum('increment', cartInfo)"
              >+</a
            >
          </li>
          <li class="cart-list-con6">
            <span class="sum">{{ cartInfo.skuPrice * cartInfo.skuNum }}</span>
          </li>
          <li class="cart-list-con7">
            <a
              href="javascript:;"
              class="sindelet"
              @click="showDelOne(cartInfo.skuId, index)"
              >删除</a
            >
            <br />
            <a href="#none">移到收藏</a>
          </li>
        </ul>
      </div>
    </div>
    <div class="cart-tool">
      <div class="select-all">
        <input class="chooseAll" type="checkbox" v-model="checkAll" />
        <span>全选</span>
      </div>
      <div class="option">
        <a @click="showDelMany">删除选中的商品</a>
        <a href="#none">移到我的关注</a>
        <a href="#none">清除下柜商品</a>
      </div>
      <div class="money-box">
        <div class="chosed">
          已选择 <span>{{ selectedCount }}</span
          >件商品
        </div>
        <div class="sumprice">
          <em>总价（不含运费） ：</em>
          <i class="summoney">{{ totalMoney }}</i>
        </div>
        <div class="sumbtn">
          <a class="sum-btn" href="###" target="_blank">结算</a>
        </div>
      </div>
    </div>
    <!-- 使用Dialog弹框 -->
    <Dialog :visible.sync="visible">
      <template v-slot:header> 提示 </template>
      <template>
        <p v-if="!isShow">此操作将永久删除此商品，是否继续</p>
        <p v-else>此操作将永久删除选中的这些商品，是否继续</p>
      </template>
      <template #footer>
        <div class="btn-footer">
          <button class="btn" @click="visible = !visible">取消</button>
          <button class="btn primary" @click="confirmDel(skuId)">确认</button>
        </div>
      </template>
    </Dialog>
  </div>
</template>

<script>
import {
  reqShopCartListData,
  reqChangeShopCartInfo,
  reqDelShopCart,
  reqDelShopCartMany,
  reqAddToCart,
} from "@/api";
import Dialog from "@/components/Dialog";
import { skuNumReg } from "@/utils/reg";
export default {
  name: "ShopCart",
  data() {
    return {
      cartInfoList: [],
      visible: false,
      skuId: "",
      index: "",
      skuIdList: [],
      isShow: false,
    };
  },
  components: {
    Dialog,
  },
  async mounted() {
    const result = await reqShopCartListData();
    if (result.code === 200) {
      console.log("请求购物车页面数据成功", result.data);
      this.cartInfoList = result.data[0] ? result.data[0].cartInfoList : [];
      console.log("cartInfoList", this.cartInfoList);
    } else {
      console.log("请求购物车页面数据失败", result.message);
    }
  },
  computed: {
    selectedCount() {
      return this.cartInfoList.reduce((prev, current) => {
        return prev + current.isChecked;
      }, 0);
    },
    totalMoney() {
      const isCheckedGoods = this.cartInfoList.filter((item) => {
        return item.isChecked;
      });
      return isCheckedGoods.reduce((prev, current) => {
        return prev + current.cartPrice * current.skuNum;
      }, 0);
    },
    checkAll: {
      get() {
        return this.cartInfoList.every((cartInfo) => cartInfo.isChecked === 1) && this.cartInfoList.length > 0
      },
      set(val) {
        console.log('val',val);
        this.cartInfoList.forEach((cartInfo) => {
          let isChecked = val ? 1 : 0;
          cartInfo.isChecked = isChecked;
          let skuId = cartInfo.skuId
          //逐个发请求，修改后台的ischecked
          this.checkCartInfoState({skuId,isChecked:1- isChecked});
        });
      },
    },
  },
  methods: {
    //切换选中状态，并发送请求
    async checkCartInfoState(cartInfo) {
      let isChecked = 1 - cartInfo.isChecked;
      const result = await reqChangeShopCartInfo(cartInfo.skuId, isChecked);
      if (result.code === 200) {
        cartInfo.isChecked = isChecked;
      } else {
        console.log(result.message);
      }
    },
    //单击确认按钮，删除对应的商品
    async confirmDel(skuId) {
      //删除多个
      if (this.isShow) {
        const result = await reqDelShopCartMany({ data: this.skuIdList });
        if (result.code === 200) {
          this.skuIdList = [];
          this.cartInfoList = this.cartInfoList.filter((cartInfo) => {
            return !cartInfo.isChecked;
          });
        } else {
          console.log(result.message);
        }
      } else {
        //删除一个
        const result = await reqDelShopCart(skuId);
        if (result.code === 200) {
          console.log("result", result);
          this.skuId = "";
          this.cartInfoList.splice(+this.index, 1);
          this.index = "";
        } else {
          console.log(result.message);
        }
      }
      this.visible = false;
    },
    //单击删除按钮，获取skuId，并弹出提示框
    showDelOne(skuId, index) {
      this.skuId = skuId;
      this.isShow = false;
      this.visible = true;
      this.index = index;
    },
    //单击删除选中的按钮，弹出提示框
    showDelMany() {
      this.cartInfoList.forEach((cartInfo) => {
        if (cartInfo.isChecked) {
          this.skuIdList.push(cartInfo.skuId);
        }
      });
      this.isShow = true;
      this.visible = true;
    },
    //修改sku的数量并发送请求
    async changeSkuNum(type, cartInfo, $event) {
      let num = 0;
      let { skuId } = cartInfo;
      switch (type) {
        case "increment":
          cartInfo.skuNum++; //通过深度数据劫持，修改cartInfoList上的数据，通过响应式数据引发视图更新
          num++; //要传给服务器的数据
          if (cartInfo.skuNum > 200) {
            cartInfo.skuNum = 200;
            num = 0;
          }
          break;
        case "decrement":
          cartInfo.skuNum--;
          num--;
          if (cartInfo.skuNum < 1) {
            cartInfo.skuNum = 1;
            num = 0;
          }
          break;
        case "change":
          let newSkuNum = $event.target.value; //获取用户输入的值
          let originCartInfoSkuNum = cartInfo.skuNum; //储存原值
          if (skuNumReg.test(newSkuNum)) {
            console.log("newSkuNum", newSkuNum);
            if (newSkuNum > 200) {
              num = 200 - cartInfo.skuNum;
              cartInfo.skuNum = 200;
            } else {
              num = newSkuNum - cartInfo.skuNum;
              cartInfo.skuNum = newSkuNum;
            }
          } else {
            $event.target.value = originCartInfoSkuNum;
          }
          break;
      }

      //判断，如果num=0即改变的数量为0则不需要发请求
      if (num === 0) return;
      await reqAddToCart(skuId, num);
    },
  },
  watch: {
    visible: {
      immediate: true, //一开始就开启监视
      handler() {
        if (this.visible) {
          document.documentElement.style.overflow = "hidden";
        } else {
          document.documentElement.style.overflow = "auto";
        }
      },
    },
  },
};
</script>

<style lang="less" scoped>
.cart {
  width: 1200px;
  margin: 0 auto;
  h4 {
    margin: 9px 0;
    font-size: 14px;
    line-height: 21px;
  }
  .cart-main {
    .cart-th {
      background: #f5f5f5;
      border: 1px solid #ddd;
      padding: 10px;
      overflow: hidden;
      & > div {
        float: left;
      }
      .cart-th1 {
        width: 25%;
        input {
          vertical-align: middle;
        }
        span {
          vertical-align: middle;
        }
      }
      .cart-th2 {
        width: 25%;
      }
      .cart-th3,
      .cart-th4,
      .cart-th5,
      .cart-th6 {
        width: 12.5%;
      }
    }
    .cart-body {
      margin: 15px 0;
      border: 1px solid #ddd;
      .cart-list {
        padding: 10px;
        border-bottom: 1px solid #ddd;
        overflow: hidden;
        & > li {
          float: left;
        }
        .cart-list-con1 {
          width: 15%;
        }
        .cart-list-con2 {
          width: 35%;
          img {
            width: 82px;
            height: 82px;
            float: left;
          }
          .item-msg {
            float: left;
            width: 150px;
            margin: 0 10px;
            line-height: 18px;
          }
        }
        .cart-list-con4 {
          width: 10%;
        }
        .cart-list-con5 {
          width: 17%;
          .mins {
            border: 1px solid #ddd;
            border-right: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
          }
          input {
            border: 1px solid #ddd;
            width: 40px;
            height: 33px;
            float: left;
            text-align: center;
            font-size: 14px;
          }

          .plus {
            border: 1px solid #ddd;
            border-left: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
          }
        }

        .cart-list-con6 {
          width: 10%;

          .sum {
            font-size: 16px;
          }
        }

        .cart-list-con7 {
          width: 13%;

          a {
            color: #666;
          }
        }
      }
    }
  }
  .cart-tool {
    overflow: hidden;
    border: 1px solid #ddd;

    .select-all {
      padding: 10px;
      overflow: hidden;
      float: left;

      span {
        vertical-align: middle;
      }

      input {
        vertical-align: middle;
      }
    }

    .option {
      padding: 10px;
      overflow: hidden;
      float: left;

      a {
        float: left;
        padding: 0 10px;
        color: #666;
      }
    }

    .money-box {
      float: right;

      .chosed {
        line-height: 26px;
        float: left;
        padding: 0 10px;
      }

      .sumprice {
        width: 200px;
        line-height: 22px;
        float: left;
        padding: 0 10px;

        .summoney {
          color: #c81623;
          font-size: 16px;
        }
      }

      .sumbtn {
        float: right;

        a {
          display: block;
          position: relative;
          width: 96px;
          height: 52px;
          line-height: 52px;
          color: #fff;
          text-align: center;
          font-size: 18px;
          font-family: "Microsoft YaHei";
          background: #e1251b;
          overflow: hidden;
        }
      }
    }
  }
}
.btn-footer {
  position: absolute;
  right: 40px;
  bottom: 20px;
  .btn {
    width: 62px;
    height: 32px;
    font-size: 14px;
    margin-left: 16px;
    border-width: 1px;
    &.primary {
      background-color: rgba(22, 175, 137, 0.918);
    }
  }
}
</style>